package com.lsh.controller;

import com.lsh.domain.User;
import com.lsh.exception.SysException;
import com.lsh.service.ArticleService;
import com.lsh.service.LoginService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

/**
 * 注册与登录模块
 */
@Controller
public class LoginController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private LoginService loginService;

    @Autowired
    private ArticleService articleService;

    /**
     * 跳转登录页面
     * @return
     */
    @RequestMapping("/login")
    public String login(){
        return "/login";
    }

    /**
     * 注册
     * @return
     */
    @RequestMapping(value = "/reg", method = RequestMethod.POST)
    public ModelAndView reg(User user, ModelAndView mv){
        boolean result = loginService.regUser(user);
        if(!result){
            mv.addObject("errorMsg", "用户名，密码或邮箱不能为空");
            mv.setViewName("/error");
        }
        mv.setViewName("/login");
        return mv;
    }

    /**
     * 登录
     * @param user
     * @returns
     */
    @ResponseBody
    @PostMapping(value = "/log", produces = {"application/json;charset=UTF-8"})
    public String login(User user, ModelAndView mv, @RequestParam("CTOKEN") String cToken,
                        HttpServletRequest request, HttpServletResponse response){
        HashMap<String, String> result = new HashMap<>();
        if(StringUtils.isEmpty(cToken)){ //判断验证码CTOKEN是否存在
            result.put("resultCode", "1003");
            result.put("resultMsg", "验证码已过期");
        }else{ //比较验证码是否正确
            String correctCode = (String) redisTemplate.opsForValue().get(cToken);
            if(!correctCode.equalsIgnoreCase(user.getCaptchaCode())){
                result.put("resultCode", "1003");
                result.put("resultMsg", "验证码错误");
            }else{ //判断用户名和密码是否正确
                String token = loginService.loginUser(user);
                if(token == null){
                    result.put("resultCode", "1002");
                    result.put("resultMsg", "用户或密码错误");
                }else{ //登陆成功并向客户端发送登陆状态TOKEN
                    addCookie(token, request, response);
                    result.put("resultCode", "1001");
                }
            }
        }
        JSONObject jo = new JSONObject();
        jo.putAll(result);
        return jo.toString();
    }

    /**
     * 未登录用户首页
     * @return
     */
    @RequestMapping("/index")
    public ModelAndView index(ModelAndView mv){
        List articles = articleService.findArticleList();
        mv.addObject("articles", articles);
        mv.setViewName("/index");
        return mv;
}

    /**
     * 添加cookie
     * @param token
     * @param request
     * @param response
     */
    public static void addCookie(String token, HttpServletRequest request, HttpServletResponse response){
        Cookie cookie = new Cookie("TOKEN", token);
        cookie.setPath(request.getContextPath() + "/");
        cookie.setMaxAge(365*30*30*60);
        response.addCookie(cookie);
    }

}
